package com.nf.teamwork.mall.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @Author: LJP
 * @Classname MailUtil
 * @Date: 2020-03-02 11:52
 * @Description: 发送邮件
 */
public final class MailUtil implements Runnable {
    /**
     * email : 收件人邮箱
     */
    private String email;
    /**
     * emailCode : 激活码
     */
    private String emailCode;

    /**
     * account: 系统生成账号
     */
    private String account;

    public MailUtil(String email, String emailCode, String account) {
        this.email = email;
        this.emailCode = emailCode;
        this.account = account;
    }

    @Override
    public void run() {
        // 1.创建连接对象javax.mail.Session
        // 2.创建邮件对象 javax.mail.Message
        // 3.发送一封激活邮件
        /**
         * 1530937232@qq.com : 发件人电子邮箱
         */
        String from = "1530937232@qq.com";
        /**
         * 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)
         */
        String host = "smtp.qq.com";

        /**
         * System.getProperties() ： 获取系统属性
         * setProperty("mail.smtp.host", host) ： 设置邮件服务器
         * setProperty("mail.smtp.auth", "true") ： 打开认证
         */
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.auth", "true");

        try {
            //QQ邮箱需要下面这段代码，163邮箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            // 1.获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("1530937232@qq.com", "abccokarctalgdji"); // 发件人邮箱账号、授权码
                }
            });

            // 2.创建邮件对象
            Message message = new MimeMessage(session);
            // 2.1设置发件人
            message.setFrom(new InternetAddress(from));
            // 2.2设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3设置邮件主题
            message.setSubject("账号激活");
            // 2.4设置邮件内容
            String content = ActivateMail.mailContent(account, emailCode);
            message.setContent(content, "text/html;charset=UTF-8");
            // 3.发送邮件
            Transport.send(message);
            System.out.println("邮件成功发送!");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送邮件时发生异常" + e);
        }
    }
}